package com.example.day_day_up.servlet;

import com.example.day_day_up.entity.constants.Constants;
import com.example.day_day_up.entity.vo.WebExamVO;
import com.example.day_day_up.entity.vo.WebMaterialVO;
import com.example.day_day_up.entity.dto.WebUserDTO;
import com.example.day_day_up.entity.po.Course;
import com.example.day_day_up.service.CourseService;
import com.example.day_day_up.service.ExamService;
import com.example.day_day_up.service.MaterialService;
import com.example.day_day_up.utils.JsonUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/course")
public class CourseServlet extends HttpServlet {
    private CourseService courseService;
    private MaterialService materialService;
    private ExamService examService;

    @Override
    public void init() throws ServletException {
        super.init();
        ServletContext servletContext = getServletContext();
        courseService = (CourseService) servletContext.getAttribute("courseService");
        materialService = (MaterialService) servletContext.getAttribute("materialService");
        examService = (ExamService) servletContext.getAttribute("examService");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 该ID为课程编号
        String id = req.getParameter("id");
        // 首页课程信息
        if (null == id) {
            List<Course> courses = courseService.getAllCourses();
            HttpSession session = req.getSession();
            session.setAttribute(Constants.COURSES_KEY, courses);
            JsonUtils.writeSuccessResponse(resp, "首页课程信息获取成功");
        }
        // 课程详细信息
        else {
            // 获取课程信息
            Course course = courseService.selectByID(id);
            HttpSession session = req.getSession();
            session.setAttribute(Constants.COURSE_KEY + id, course);

            WebUserDTO currentUser = (WebUserDTO) session.getAttribute(Constants.USER_KEY);
            String uId = currentUser.getId();
            // 获取课程对应资料信息
            List<WebMaterialVO> materials = materialService.selectMaterialByCIDAndUID(id, uId);
            if (!materials.isEmpty()) {
                session.setAttribute(Constants.MATERIALS_KEY + id, materials);
            }

            // 获取课程对应考试信息
            List<WebExamVO> exams = examService.getExamsByCIDAndUID(id, uId);
            if (!exams.isEmpty()) {
                session.setAttribute(Constants.EXAMS_KEY + id, exams);
            }
            JsonUtils.writeSuccessResponse(resp, "课程详细信息获取成功");
        }
    }
}
